package com.dzm.content.service.impl;

import com.dzm.constants.RedisConstant;
import com.dzm.content.service.TokenService;
import com.dzm.to.LoginUser;
import com.dzm.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 作者：Dzm
 * 时间：2024-09-13-19:34
 * 功能：
 */

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Map<String, Object> createToken(LoginUser loginUser) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        loginUser.setUserId(uuid);
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", loginUser.getUser().getUsername());
        claims.put("user_id", loginUser.getUser().getId());
        claims.put("access_id", loginUser.getUserId());

        String token = JwtUtil.createToken(claims);

        //将用户信息存入缓存
        redisTemplate.opsForValue().set(RedisConstant.LOGIN_TOKEN + uuid, loginUser, 1, TimeUnit.DAYS);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);

        return resultMap;
    }
}
